package com.zfc.mymall.product.exception;

import com.zfc.common.exception.BizCodeEnum;
import com.zfc.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @description: TODO
 * @author: shenchong
 * @date: 2021/12/14 15:02
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.zfc.mymall.product.controller")
public class ExceptionControllerAdvice {

  @ExceptionHandler(value = MethodArgumentNotValidException.class)
  public R handleVaildException(MethodArgumentNotValidException e) {
    BindingResult result = e.getBindingResult();

    //  获取校验错误信息
    HashMap<String, String> errMap = new HashMap<>();
    result.getFieldErrors().forEach(item -> {
      String msg = item.getDefaultMessage();
      String filed = item.getField();
      errMap.put(filed, msg);
    });
    return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(), BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data", errMap);
  }

  @ExceptionHandler(value = Throwable.class)
  public R handleException(Throwable throwable){
    log.error("系统未知异常：{}, 异常类型：{}", throwable.getMessage(), throwable.getClass());
    return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
  }
}
